/*
 * @Author: yangrongxin
 * @Date: 2021-04-27 10:42:06
 * @LastEditors: guoju
 * @LastEditTime: 2022-01-07 11:28:55
 */
import React, { useEffect, useState, useRef } from 'react';
import Taro from '@tarojs/taro';
import { View, ScrollView } from '@tarojs/components';
import LotteryEmpty from '@/components/LotteryEmpty';
import VideoProvider from './provider';
import { getArticleList } from '../../service';
import ArticleItem from './components/ArticleItem/';
import VideoItem from './components/VideoItem';
import styles from './index.module.less';

// TODO: 当前组件与scrollContent进行集合
interface ISearchResultProps {
  searchParam: {
    tag?: string;
    moduleCode: string;
  };
  containerStyle?: any;
  isScrollView?: boolean;
  emptyNotice?: any; // 当前选择没有数据内容的提示
  isSearchParam?: any; // 返回当前是否进行加载的方法
}

export enum ARTICLE_TYPE {
  ARTICLE = '1', // 对应文章
  VIDEO = '2', // 对应视频
}

/**
 * @description 展示搜索结果
 * @param {*} props
 * @returns
 */
const SearchResult = (props: ISearchResultProps) => {
  const pageSize = 10; // 存储当前的分页数据

  const {
    searchParam = {
      tag: '',
      moduleCode: '',
    },
    containerStyle,
    isScrollView = true,
    emptyNotice = '数据为空',
    isSearchParam = true,
  } = props;

  const [articleList, setArticleList] = useState<any[]>([]);
  const [pageNum, setPageNum] = useState<number>(1);
  const [canLoadingMore, setCanLoadingMore] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const [playVideoId, setPlayVideoId] = useState<string>('');
  const [refresherTrigger, setRefresherTrigger] = useState<boolean>(false);
  const LotteryEmptyRef = useRef();

  const showLottie = () => {
    setTimeout(() => {
      const lotteryEmptyRef: any = LotteryEmptyRef?.current;
      lotteryEmptyRef?.initLottie();
    }, 500);
  };

  useEffect(() => {
    const canLoad: boolean = typeof isSearchParam === 'function' ? isSearchParam() : isSearchParam;
    if (canLoad) getArticleListFn(false);
    if (!searchParam.moduleCode) {
      setArticleList([]);
      showLottie();
    }
  }, [searchParam.tag, searchParam.moduleCode]);

  const getArticleListFn = (isLoadMore = true) => {
    setLoading(true);
    getArticleList({
      pageNum,
      pageSize,
      ...searchParam,
      // query: searchParam,
    }).then((res: any) => {
      setLoading(false);
      console.log('searchResult', res);
      const resData = res;
      if (Array.isArray(resData?.content) && resData?.content.length !== 0) {
        const newArticleList = isLoadMore ? articleList.concat(resData.content) : resData.content;
        setArticleList(newArticleList);
        setCanLoadingMore(resData.total > newArticleList.length);
      } else {
        setArticleList([]);
        setCanLoadingMore(false);
        setTimeout(() => {
          showLottie();
        }, 500);
      }
    });
  };

  const ContentElement = React.memo(() => (
    <View className={styles.content}>
      {articleList.map((item: any) => {
        const { type } = item;
        if (String(type) === ARTICLE_TYPE.ARTICLE) {
          return <ArticleItem key={`article-${Math.random()}`} {...item} />;
        }
        return <VideoItem key={`video-${Math.random()}`} {...item} />;
      })}
    </View>
  ));

  if (!Array.isArray(articleList) || articleList.length === 0) {
    return <LotteryEmpty ref={LotteryEmptyRef} emptyNotice={emptyNotice} />;
  }

  if (isScrollView) {
    return (
      <ScrollView
        className={containerStyle || styles.container}
        scrollY
        scrollWithAnimation
        onScrollToLower={() => {
          if (canLoadingMore && !loading) {
            let newPageNum: number = pageNum;
            setPageNum((newPageNum += 1));
            getArticleListFn();
          }
        }}
        refresherEnabled
        onRefresherRefresh={() => {
          setRefresherTrigger(true);
          getArticleListFn();
        }}
        refresherTriggered={refresherTrigger}
      >
        <ContentElement />
      </ScrollView>
    );
  }

  return (
    <View className={containerStyle || styles.container}>
      <ContentElement />
    </View>
  );
};

export default React.memo(SearchResult, (preProps: any, nextProps: any) => {
  if (
    preProps.searchParam.tag === nextProps.searchParam.tag &&
    preProps.searchParam.moduleCode === nextProps.searchParam.moduleCode &&
    preProps.emptyNotice === nextProps.emptyNotice
  ) {
    return true;
  }
  return false;
});
